
package com.rt.schedulenew.utils.util;
import java.lang.reflect.Field;
import java.util.List;
import java.util.ArrayList;
import com.rt.schedulenew.utils.model.ItemNotice;
import javax.xml.transform.Transformer;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.TransformerFactory;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.Map;
import org.apache.commons.lang3.StringEscapeUtils;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.JAXBException;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.io.StringWriter;
import javax.xml.bind.Marshaller;
import javax.xml.bind.JAXBContext;
public class JaxbXmlUtil
{
    private static final String DEFAULT_ENCODING = "UTF-8";
    
    public static String convertToXml(final Object obj) {
        return convertToXml(obj, "UTF-8", false);
    }
    
    public static String convertToXmlNotIgnoreBlank(final Object obj) {
        return convertToXml(obj, "UTF-8", true);
    }
    
    private static String convertToXml(final Object obj, final String encoding, final boolean notIgnoreBlank) {
        String result = null;
        try {
            final JAXBContext context = JAXBContext.newInstance(new Class[] { obj.getClass() });
            final Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty("jaxb.formatted.output", (Object)true);
            marshaller.setProperty("jaxb.encoding", (Object)encoding);
            if (notIgnoreBlank) {
                marshaller.setListener((Marshaller.Listener)new MarshallerListener());
            }
            final StringWriter writer = new StringWriter();
            marshaller.marshal(obj, (Writer)writer);
            result = writer.toString();
        }
        catch (Exception e) {
            throw new RuntimeException("解析失败", e);
        }
        return result;
    }
    
    public static <T> T convertToJavaBean(final String xml, final Class<T> clazz) {
        T obj = null;
        try {
            final JAXBContext context = JAXBContext.newInstance(new Class[] { clazz });
            final Unmarshaller unmarshaller = context.createUnmarshaller();
            obj = (T)unmarshaller.unmarshal((Reader)new StringReader(xml));
        }
        catch (JAXBException e) {
            throw new RuntimeException("解析失败", (Throwable)e);
        }
        return obj;
    }
    
    public static String delXmlHead(String xmlStr) {
        xmlStr = StringEscapeUtils.unescapeXml(xmlStr);
        if (xmlStr.indexOf("<?") >= 0) {
            final int beginIndex = xmlStr.indexOf("<?");
            final int endIndex = xmlStr.indexOf("?>", beginIndex);
            final String xmlHead = xmlStr.substring(beginIndex, beginIndex + endIndex + 2);
            xmlStr = xmlStr.replace(xmlHead, "");
        }
        return xmlStr.trim();
    }
    
    public static String mapToXml(final Map<String, String> data) {
        try {
            final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            final Document document = documentBuilder.newDocument();
            final Element root = document.createElement("notice");
            document.appendChild(root);
            for (final String key : data.keySet()) {
                String value = data.get(key);
                if (value == null) {
                    value = "";
                }
                value = value.trim();
                final Element filed = document.createElement(key);
                filed.appendChild(document.createTextNode(value));
                root.appendChild(filed);
            }
            final TransformerFactory tf = TransformerFactory.newInstance();
            tf.setAttribute("http://javax.xml.XMLConstants/property/accessExternalDTD", "");
            tf.setAttribute("http://javax.xml.XMLConstants/property/accessExternalStylesheet", "");
            final Transformer transformer = tf.newTransformer();
            final DOMSource source = new DOMSource(document);
            transformer.setOutputProperty("encoding", "UTF-8");
            transformer.setOutputProperty("indent", "yes");
            final StringWriter writer = new StringWriter();
            final StreamResult result = new StreamResult(writer);
            transformer.transform(source, result);
            final String output = writer.getBuffer().toString();
            writer.close();
            return delXmlHead(output);
        }
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public static void main(final String[] args) {
        final ItemNotice itemNotice = new ItemNotice();
        final List<ItemNotice.Notice> notices = new ArrayList<ItemNotice.Notice>();
        final ItemNotice.Notice notice1 = new ItemNotice.Notice();
        notice1.setMaxDays("1");
        notices.add(notice1);
        final ItemNotice.Notice notice2 = new ItemNotice.Notice();
        notice1.setMaxDays("2");
        notices.add(notice2);
        itemNotice.setNotices(notices);
        final String xml = convertToXml(itemNotice);
        final String xml2 = "<notices>\n    <notice>\n        <minDays>1</minDays>\n        <maxDays>344</maxDays>\n        <patientSource>门诊</patientSource>\n        <text>注意空腹</text>\n    </notice>\n    <notice>\n        <taboo>预约须知内容</taboo>\n    </notice>\n    <notice>\n        <smsDays>2</smsDays>\n        <smsTime>短信发送时间</smsTime>\n        <smsApmStartTime>短信发送时段开始时间</smsApmStartTime>\n        <smsApmEndTime>短信发送时段结束时间</smsApmEndTime>\n        <smsContent>短信发送内容</smsContent>\n    </notice>\n</notices>\n";
        System.out.println(xml);
        final String xml3 = delXmlHead(xml2);
        final ItemNotice itemNotice2 = convertToJavaBean(xml3, ItemNotice.class);
        System.out.println(itemNotice2);
    }
    
    public static class MarshallerListener extends Marshaller.Listener
    {
        public static final String BLANK_CHAR = "";
        
        public void beforeMarshal(final Object source) {
            super.beforeMarshal(source);
            final Field[] declaredFields;
            final Field[] fields = declaredFields = source.getClass().getDeclaredFields();
            for (final Field f : declaredFields) {
                f.setAccessible(true);
                try {
                    if (f.getType() == String.class && f.get(source) == null) {
                        f.set(source, "");
                    }
                }
                catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
